var $saveBtn;
var $addressForm;

var $receiveName;
var $receivePhone;
var $receiveAddress;
var $isDefault;

var user;
var address;

function init() {
    $saveBtn = $('#saveBtn');
    $addressForm = $('#addressForm');

    $receiveName = $('#receiveName');
    $receivePhone = $('#receivePhone');
    $receiveAddress = $('#receiveAddress');
    $isDefault = $('#isDefault');

    user = JSON.parse($.cookie("user"));
    var id = $.webUtil.getQueryString("id");
    if (id) {
        mui.ajax($.constant.webRoot() + 'v1/address/' + id, {
            dataType: 'json',
            type: 'GET',
            async: false,
            success: function (data) {
                address = data;
            }
        });
    }
}

function initView() {

    if (address) {
        $receiveName.val(address.receiveName);
        $receivePhone.val(address.receivePhone);
        $receiveAddress.val(address.receiveAddress);
        if (address.isDefault && address.isDefault === "1") {
            mui("#isDefault").switch().toggle();
        }
    }

    $saveBtn.bind('tap', function () {
        var value = $addressForm.serializeObject();
        var isActive = $isDefault[0].classList.contains("mui-active");
        var isDefault = (isActive === true ? '1' : '0');
        value.isDefault = isDefault;
        value.userId = user.id;
        if (address) {
            value.id = address.id;
        }

        var check = true;
        $("#addressForm").find('[name]').each(function () {
            if (!this.value || this.value.trim() === "") {
                mui.alert(this.placeholder + "不允许为空");
                check = false;
                return false;
            }
        });

        if (!check) {
            return;
        }

        mui.ajax($.constant.webRoot() + 'v1/address', {
            dataType: 'json',
            type: (address == null ? 'POST' : 'PUT'),
            headers: {'Content-Type': 'application/json'},
            data: JSON.stringify(value),
            success: function (data) {
                if (data.code === 200) {
                    mui.back();
                } else {
                    mui.toast('修改失敗');
                }

            }
        });

    });
}

$(function () {
    init();
    initView();

});